package com.fingard.dsp.bank.directbank.cmbc01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

@Component("CMBC01BatPayRec")
public class CMBC01BatPayRec extends CMBC01Base implements IBatPayRec {
	//1988
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_reqBat) throws Exception{
		//返回ATS的对象
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		try {
			CMBC01Header bankHeader = new CMBC01Header();
			if(p_reqBat.reqHeader.commandCode.equals("198802")){
				bankHeader.trnCode = "batchCostReimb";//198802	批量代付（工资、报销）
			}
			else{
				bankHeader.trnCode = "batchXfer";//198801	批量代付
			}
			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			//写入通用的头部节点
			writeCommonHeader(xmlWriter, bankHeader);
			xmlWriter.writeStartElement("xDataBody");
			xmlWriter.writeElementString("trnId", p_reqBat.reqBatchNO);
			xmlWriter.writeElementString("insId", p_reqBat.reqBatchNO);
			xmlWriter.writeElementString("cltcookie", p_reqBat.reqBatchNO);
			String bkUsage = "";
			if(p_reqBat.reqHeader.commandCode.equals("198802")){
				xmlWriter.writeElementString("PayerAcNo", p_reqBat.ownAct);
				bkUsage = getBankConfig().getMapValueByKey("usage1988", p_reqBat.useType);
				if(bkUsage.equals("4111")){//4111  工资奖金
					xmlWriter.writeElementString("payType", "1");
				}
				else{
					xmlWriter.writeElementString("payType", "2");
				}
			}
			else{
				xmlWriter.writeElementString("payerAcct", p_reqBat.ownAct);
				xmlWriter.writeElementString("payType", "0");
			}
			
			xmlWriter.writeElementString("totalRow", p_reqBat.totalNum);
			xmlWriter.writeElementString("totalAmt", p_reqBat.totalAmt);
			if(p_reqBat.reqHeader.commandCode.equals("198802")){
				xmlWriter.writeElementString("Usage", bkUsage);
			}
			StringBuilder tmpSbData = new StringBuilder();
			int tmpCount = 0;
			while(p_reqBat.readRecord()){
				tmpCount++;
				if(tmpCount > 1){
					tmpSbData.append("^");
				}
				ReqPayRecDetail eachDetail = p_reqBat.readedDetail;
				if(p_reqBat.reqHeader.commandCode.equals("198802")){
					//收款账号|收款账户名 |备注（预留、暂不支持）|金额 |凭证号
					tmpSbData.append(eachDetail.recAct+"|");
					tmpSbData.append(eachDetail.recName+"|");
					//备注
					tmpSbData.append(eachDetail.purpose.replace("|", "-")+"|");
					tmpSbData.append(eachDetail.payAmount+"|");
					tmpSbData.append(eachDetail.askNumber);
				}
				else{
					/*
					支付文件数据格式<fileContent>：
					汇路|凭证号|支付业务种类|业务种类代码|收款帐户类型|收款账号|收款户名|收款行联行号|收款行名|备注|发送短信给收款方标识|收款方手机号|收款方email地址|常用用途代码|金额^汇路|凭证号|支付业务种类|业务种类代码|收款帐户类型|收款账号|收款户名|收款行联行号|收款行名|备注|发送短信给收款方标识|收款方手机号|收款方email地址|常用用途代码|金额

									 * */
					
					String huilu="";//行内交易输入0；   跨行交易汇路为: 6小额实时支付   7大额实时支付   11网银互联

					if(eachDetail.sameBnk.equals("1")){
						huilu = "0";
					}
					else if(eachDetail.isLargeAmt()){
						huilu = "7";
					}
					else{
						huilu = "6";
					}
					tmpSbData.append(huilu+"|");
					tmpSbData.append(eachDetail.askNumber+"|");//凭证号
					tmpSbData.append("|");//支付业务种类	可不输入
					tmpSbData.append("|");//业务种类代码	可不输入
					//收款帐户类型	必输 0.企业 1.个人卡  2.个人折
					if(eachDetail.isPrivate.equals("1")){
						if(eachDetail.sameBnk.equals("1") && eachDetail.cardType.equals("1")){
							tmpSbData.append("2|");
						}
						else{
							tmpSbData.append("1|");
						}
					}
					else{
						tmpSbData.append("0|");
					}
					//收款账号|收款户名
					tmpSbData.append(eachDetail.recAct+"|");
					tmpSbData.append(eachDetail.recName+"|");
					//收款行联行号|收款行名
					if(eachDetail.sameBnk.equals("1")){
						tmpSbData.append("|");
						tmpSbData.append("|");
					}
					else{
						tmpSbData.append(eachDetail.cnapsCode+"|");
						tmpSbData.append(eachDetail.cnapsName+"|");
					}
					//备注
					tmpSbData.append(eachDetail.purpose.replace("|", "-")+"|");
					//发送短信给收款方标识|收款方手机号|收款方email地址|
					tmpSbData.append("|||");
					//常用用途代码
					tmpSbData.append("|");
					//金额
					tmpSbData.append(eachDetail.payAmount);
				}
			}
			xmlWriter.writeElementString("fileContent", tmpSbData.toString());
			xmlWriter.writeEndDocument();//写入报文完成
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
			if(tmpStrRet[0].length() == 0){
				StringBuilder tmpSbMsg = new StringBuilder();
				//解析银行返回
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if(tmpBkReader != null){
					String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
					String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
					if(!StringHelper.isNullOrEmpty(tmpRetCode)){
						retAts.respCode = "0";
						retAts.respInfo = tmpRetMessage;
						retAts.transState = tmpRetCode;
						retAts.payInfoCode = tmpRetCode;
						retAts.reqSeqID = tmpBkReader.getFirstText("/CMBC/xDataBody/batchTransfers/insId");
					}
					else{
						retAts.respCode = "-1";
						retAts.respInfo = tmpRetMessage;
					}
				}
				else if(tmpStrRet[1].indexOf("Connection refused")>=0){
					retAts.respCode = "0";
					retAts.respInfo = tmpStrRet[1];
					retAts.reqSeqID = p_reqBat.reqBatchNO;
					retAts.transState = PaymentState.FAIL_Batch;
					retAts.payInfoCode = "E9999";
				}
				else{
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			}
			else if(tmpStrRet[0].equals(ConnState.FAIL)){
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			}
			else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
			
		}catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.toString();
			e.printStackTrace();
		}
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_reqBat.reqBatchNO;
		}
		retAts.writeRetToATS();
		return retAts;		
	}
	//9188
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_reqBat) throws Exception{
		//返回ATS的对象
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		retAts.respCode = "0";
		retAts.reqSeqID = p_reqBat.reqBatchNO;
		retAts.transState = PaymentState.FAIL_Batch;
		retAts.payInfoCode = "E1301";
		retAts.respInfo = "民生不支持批量代收";
		retAts.writeRetToATS();
		return retAts;
	}
	
	//批量代收和批量代付提交
	//public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception{
		
	//}

	//1998 状态查询
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_reqQryBat) throws Exception{
		//返回ATS的对象
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		retAts.respCode = "";

		CMBC01Header bankHeader = new CMBC01Header();
		if(p_reqQryBat.reqHeader.commandCode.equals("198802")){
			bankHeader.trnCode = "qryBatchCostReimb";//198802	批量代付（工资、报销）
		}
		else{
			bankHeader.trnCode = "qryBatchXfer";//198801	批量代付
		}
		
		XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
		writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
		
		xmlWriter.writeStartElement("xDataBody");
		xmlWriter.writeElementString("trnId", p_reqQryBat.reqHeader.transSeqID);
		xmlWriter.writeElementString("insId", p_reqQryBat.reqBatchNO);
		if(p_reqQryBat.reqHeader.commandCode.equals("198802")){
			String bkUsage = getBankConfig().getMapValueByKey("usage1988", p_reqQryBat.useType);
			if(bkUsage.equals("4111")){//4111  工资奖金
				xmlWriter.writeElementString("payType", "1");
			}
			else{
				xmlWriter.writeElementString("payType", "2");
			}
		}
		else{
			xmlWriter.writeElementString("payType", "0");
		}
		
		xmlWriter.writeEndDocument();
		try{
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if(tmpStrRet[0].length() == 0){
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if(tmpBkReader != null){
					String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
					String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
					String insId = tmpBkReader.getFirstText("/CMBC/xDataBody/batchTransfers/insId");
					if(tmpRetCode.equals("0")){
						retAts.respCode = "0";
						retAts.reqSeqID = insId;
						
                        String statusCode = tmpBkReader.getFirstText("/CMBC/xDataBody/statusId/statusCode");
                        String statusErrMsg = tmpBkReader.getFirstText("/CMBC/xDataBody/statusId/statusErrMsg");
                        String statusSeverity = tmpBkReader.getFirstText("/CMBC/xDataBody/statusId/statusSeverity");
						String fileContent = tmpBkReader.getFirstText("/CMBC/xDataBody/batchTransfers/fileContent");
						
						if(statusCode.equals("0") || StringHelper.hasAnyChar(fileContent)){
							retAts.writeBeforeDetail();
							String[] resultArray = fileContent.split("^");
							for(int i=0;i<resultArray.length;i++){
								if(resultArray[i].trim().length() > 0){
									String[] tmpEachArr = resultArray[i].split("\\|");
									RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
									if(p_reqQryBat.reqHeader.commandCode.equals("198802")){
										/*
										收款账号32|收款人名称60 |备注（预留，暂不支持） |[3]金额15,2|[4]交易状态2|[5]错误信息80|[6]凭证号8（该列请求时有凭证号列，该列原值返回；否则不返回此列）
																			 * */
										tmpRetDetail.postScript = tmpEachArr[6];
										tmpRetDetail.recAct = tmpEachArr[0];
										tmpRetDetail.recName = tmpEachArr[1];
										tmpRetDetail.payAmount = tmpEachArr[3];
										tmpRetDetail.result = statusCode + "+" + statusSeverity + "+" + tmpEachArr[4];
										tmpRetDetail.payInfoCode = tmpEachArr[5];
										tmpRetDetail.memo = tmpEachArr[5];
									}
									else{
									/*
									凭证号 13|付款人帐号32|付款人名称60|付款人行名40|[4]收款人账号32|收款人名称60|收款行行名40|[7]金额15,2|[8]交易状态2|[9]错误信息80^凭证号|收款人账号|收款人名称|收款行联行号|金额|交易状态|错误信息
																 * */
										tmpRetDetail.postScript = tmpEachArr[0];
										tmpRetDetail.recAct = tmpEachArr[4];
										tmpRetDetail.recName = tmpEachArr[5];	
										tmpRetDetail.payAmount = tmpEachArr[7];
										tmpRetDetail.result = statusCode + "+" + statusSeverity + "+" + tmpEachArr[8];
										tmpRetDetail.payInfoCode = tmpEachArr[9];
										tmpRetDetail.memo = tmpEachArr[9];
									}
									retAts.writeRetDetail(tmpRetDetail);
								}
							}
						}
						else{
							retAts.transState = statusCode + "+" + statusSeverity + "+" + statusErrMsg;
							retAts.respInfo = statusErrMsg;
							retAts.payInfoCode = statusCode + "+" + statusSeverity;
							retAts.writeBeforeDetail();
						}
					}
					else if(StringHelper.hasAnyChar(insId)){
						retAts.respCode = "0";
						retAts.respInfo = tmpRetMessage;
						retAts.reqSeqID = insId;
						retAts.payInfoCode = tmpRetCode;
						retAts.transState = tmpRetCode + "+" + tmpRetMessage;
						retAts.writeBeforeDetail();
					}
					else{
						retAts.respCode = "-1";
						retAts.respInfo = tmpRetMessage;
					}
				}
				else{
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			}
			else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}
		catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_reqQryBat.reqBatchNO;
		}
		if(retAts.respCode.equals("-1")){
			retAts.writeBeforeDetail();
		}
		retAts.writeAfterDetail();
		return retAts;		
	}
	//9198
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_reqQryBat) throws Exception{
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		retAts.respCode = "0";
		retAts.reqSeqID = p_reqQryBat.reqBatchNO;
		retAts.transState = PaymentState.FAIL_Batch;
		retAts.payInfoCode = "E1301";
		retAts.respInfo = "民生不支持批量代收";
		retAts.writeBeforeDetail();
		retAts.writeAfterDetail();
		return retAts;
	}
	
	//批量代收和批量代付状态查询
	//public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception{
		
	//}	
}
